package com.yuanqiworld.vw.domain;

import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import java.util.List;

@RooJavaBean
@RooToString
@RooJson
@RooJpaActiveRecord(table = "vw_metadata", finders = {"findMetadatasByCategory", "findMetadatasByCategoryAndMetadataValue"})
public class Metadata {

    @NotNull
    private String category;

    @NotNull
    private String metadataValue;

    private String metadataLabel;

    private Integer orderNumber;

    private boolean revisable = true;

    // 不能删除revisable为false的项目.
    @Transactional
    public void remove() {
        if (!revisable) throw new RuntimeException("error.metadata.cannot.delete");
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            this.entityManager.remove(this);
        } else {
            Metadata attached = Metadata.findMetadata(this.getId());
            this.entityManager.remove(attached);
        }
    }

    // 不能修改已保存的，且revisable为false的项目.
    @Transactional
    public Metadata merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (!revisable && entityManager.contains(this)) throw new RuntimeException("error.metadata.cannot.modified");
        Metadata merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }

    public static TypedQuery<Metadata> findSortedMetadatasByCategory(String category) {
        if (category == null || category.length() == 0) throw new IllegalArgumentException("The category argument is required");
        EntityManager em = Metadata.entityManager();
        TypedQuery<Metadata> q = em.createQuery("SELECT o FROM Metadata AS o WHERE o.category = :category ORDER BY o.orderNumber", Metadata.class);
        q.setParameter("category", category);
        return q;
    }
}
